﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace KongMing.Project.Common
{
    public static class Tools
    {
        public static string GUID => Guid.NewGuid().ToString("N");
        public static bool IsNull(this string s)
        {
            return string.IsNullOrWhiteSpace(s);
        }
        public static bool NotNull(this string s)
        {
            return !string.IsNullOrWhiteSpace(s);
        }
        public static int GetRandom(int minNum, int maxNum)
        {
            var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
            return new Random(seed).Next(minNum, maxNum);
        }
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
        public static object GetDefaultVal(string typename)
        {
            return typename switch
            {
                "Boolean" => false,
                "DateTime" => default(DateTime),
                "Date" => default(DateTime),
                "Double" => 0.0,
                "Single" => 0f,
                "Int32" => 0,
                "String" => string.Empty,
                "Decimal" => 0m,
                _ => null,
            };
        }
        public static void CoverNull<T>(T model) where T : class
        {
            if (model == null)
            {
                return;
            }
            var typeFromHandle = typeof(T);
            var properties = typeFromHandle.GetProperties();
            var array = properties;
            for (var i = 0; i < array.Length; i++)
            {
                var propertyInfo = array[i];
                if (propertyInfo.GetValue(model, null) == null)
                {
                    propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
                }
            }
        }
        public static void CoverNull<T>(List<T> models) where T : class
        {
            if (models.Count == 0)
            {
                return;
            }
            foreach (var model in models)
            {
                CoverNull(model);
            }
        }

        /// <summary>
        /// 获取当前时间戳
        /// </summary>
        public static long GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }

        /// <summary>
        /// 计算字符串的哈希值
        /// </summary>
        public static string ComputeHash(string str)
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            if (buffer == null || buffer.Length < 1)
                return "";
            MD5 md5 = MD5.Create();
            byte[] hash = md5.ComputeHash(buffer);
            StringBuilder sb = new StringBuilder();
            foreach (var b in hash)
                sb.Append(b.ToString("x2"));
            return sb.ToString();
        }

        /// <summary>
        /// 根据图片地址获取图片的二进制流
        /// </summary>
        public static byte[] GetImageByte(string imageUrl)
        {
            if (string.IsNullOrWhiteSpace(imageUrl))
                return null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imageUrl);
            request.Proxy = null;
            request.Accept = "*/*";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Referer = "";
            request.Timeout = 30000;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)";
            request.Method = "GET";
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                    return null;
                System.IO.MemoryStream ms = new MemoryStream();
                using (var s = response.GetResponseStream())
                    s.CopyTo(ms);
                return ms.ToArray();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
